package net.lijingye.education.controller;

import net.lijingye.education.entity.*;
import net.lijingye.education.exception.DaoException;
import net.lijingye.education.exception.ObjectNotExistsException;
import net.lijingye.education.exception.ProfileCityNotExistsException;
import net.lijingye.education.exception.ProfileProvinceNotExistsException;
import net.lijingye.education.request.PostTweetRequest;
import net.lijingye.education.request.PutProfileRequest;
import net.lijingye.education.response.BaseResponse;
import net.lijingye.education.response.ErrorResponse;
import net.lijingye.education.response.SuccessResponse;
import net.lijingye.education.response.meta.JSONParameterErrorMeta;
import net.lijingye.education.response.meta.ObjectNotExistsMeta;
import net.lijingye.education.response.meta.ProfileHomeCityNotExistsMeta;
import net.lijingye.education.response.meta.ProfileHomeProvinceNotExistsMeta;
import net.lijingye.education.service.UserService;
import net.lijingye.education.service.UtilService;
import net.lijingye.education.util.CommonUtil;
import net.lijingye.education.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LijingYe on 2016/3/26.
 */
@RestController
public class MyProfileController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private UtilService utilService;

    @RequestMapping(value = "/my/profiles", method = RequestMethod.GET)
    public BaseResponse getMyProfiles(@RequestHeader("Authorization") String accessToken) throws DaoException {
        try {
            User user = userService.getUserByAccessToken(accessToken);
            MyProfileVO myProfileVO = new MyProfileVO(user);
            return new SuccessResponse(myProfileVO);
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }

    }

    @RequestMapping(value = "/my/profiles", method = RequestMethod.PUT)
    public BaseResponse putMyProfiles(@RequestHeader("Authorization") String accessToken, @Valid @RequestBody PutProfileRequest putProfileRequest, BindingResult result) throws DaoException, ParseException {
        if (result.hasErrors()) {
            return new ErrorResponse(new JSONParameterErrorMeta());
        }
        try {
            User user = userService.getUserByAccessToken(accessToken);
            Province province = null;
            if (null != putProfileRequest.getProvince() && !putProfileRequest.getProvince().trim().equals("")) {
                province = utilService.getProvinceById(putProfileRequest.getProvince());
            }
            City city = null;
            if (null != putProfileRequest.getCity() && !putProfileRequest.getCity().trim().equals("")) {
                city = utilService.getCityById(putProfileRequest.getCity());
            }
            userService.updateUserProfile(user, putProfileRequest.getName(), putProfileRequest.getGender(), putProfileRequest.getBirthday(), putProfileRequest.getTelephone(), province, city, putProfileRequest.getHobbies(), putProfileRequest.getMotto(), putProfileRequest.getEmail());
            return new SuccessResponse(new MyProfileVO(user));
        } catch (ProfileProvinceNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ProfileHomeProvinceNotExistsMeta());
        } catch (ProfileCityNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ProfileHomeCityNotExistsMeta());
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }
    }

    @RequestMapping(value = "/my/lessons", method = RequestMethod.GET)
    public BaseResponse getMyLessons(@RequestHeader("Authorization") String accessToken, @RequestParam(value = "termId", required = false) String termId) throws DaoException {
        try {
            User user = userService.getUserByAccessToken(accessToken);
            List<Lesson> lessonList = user.getLessonList();
            List<LessonLiteVO> lessonLiteVOList = new ArrayList<>();
            lessonList.forEach(lesson -> {
                if (null == termId) {
                    lessonLiteVOList.add(new LessonLiteVO(lesson));
                } else {
                    try {
                        if (lesson.getTerm().getId() == Integer.valueOf(termId)) {
                            lessonLiteVOList.add(new LessonLiteVO(lesson));
                        }
                    } catch (NumberFormatException e) {

                    }
                }
            });
            return new SuccessResponse(lessonLiteVOList);
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }
    }

    @RequestMapping(value = "/my/visitors", method = RequestMethod.GET)
    public BaseResponse getMyVisitors(@RequestHeader("Authorization") String accessToken, @RequestParam(value = "page", required = false) String page) throws DaoException {
        try {
            User user = userService.getUserByAccessToken(accessToken);
            List<Visitor> visitorList = user.getVisitorList();
            List<VisitorVO> visitorVOList = new ArrayList<>();
            visitorList.forEach(visitor -> {
                visitorVOList.add(new VisitorVO(visitor));
            });
            return CommonUtil.splitPage(visitorVOList, page, super.getPageSize());
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }
    }

    @RequestMapping(value = "/my/tweets", method = RequestMethod.GET)
    public BaseResponse getMyTweets(@RequestHeader("Authorization") String accessToken, @RequestParam(value = "page", required = false) String page) throws DaoException {
        try {
            User user = userService.getUserByAccessToken(accessToken);
            List<Tweet> tweetList = user.getTweetList();
            List<TweetVO> tweetVOList = new ArrayList<>();
            for (Tweet tweet : tweetList) {
                if (0 == tweet.getType()) {
                    tweetVOList.add(new TweetVO(tweet, userService.getUserById(tweet.getUserId())));
                }
            }
            return CommonUtil.splitPage(tweetVOList, page, super.getPageSize());
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }

    }

    @RequestMapping(value = "/my/tweets", method = RequestMethod.POST)
    public BaseResponse postMyTweets(@RequestHeader("Authorization") String accessToken, @Valid @RequestBody PostTweetRequest postTweetRequest, BindingResult result) throws DaoException {
        if (result.hasErrors()) {
            return new ErrorResponse(new JSONParameterErrorMeta());
        }
        try {
            User user = userService.getUserByAccessToken(accessToken);
            Tweet tweet = userService.addTweet(new Date(), postTweetRequest.getContent(), user);
            if (postTweetRequest.getFile().size() > 0) {
                userService.addTweetFile(tweet.getId(), postTweetRequest.getFile());
            }
            TweetVO tweetVO = new TweetVO(tweet, user);
            return new SuccessResponse(tweetVO);
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }
    }
}
